// pages/index/index.js
var app = getApp(); //获取应用实例
const quote = app.globalData.quote;
const mta = quote.mta;
const util = quote.util;
const tools = quote.tools;
const api = quote.api;
const path = quote.paths;
const Authorize = quote.Authorize;


Page({
  data: {
    path: path,
    loginStatus: false, //登录状态
    isPromptClose: true,
    dub_num: 0,
    dailyUpdate: {},
    videoUrl: app.globalData.videoUrl,

    label_id: 0,

    DailyUpdatesList: [], //每日更新数据
    HotRecommendationList: [], //热门推荐数据
    CategoryListList: [], //视频分类数据源
    VideoCategory: [], //当前显示视频分类数据
    changeIndex: 2, //当前分类视频的编号
    thisDay: "",
    hideModal: false,
    hideRedModal: true, //隐藏红包弹窗
    hidePop: true,
    hideplaysIntroduction: true,
    hideRedActivity: true,
    animationRedPaper: '',
    animationData: '',
    isFirst: true,
    loadingHidden: false,
    Dailychallenge: 1, //是否为挑战视频
    scaleH: app.globalData.scaleH || 1,
    DefaultTimes: 0, //每日挑战的默认练习次数
    AccountsTimes: 0, //账户中获取的练习次数
    hideloadmore: true,
    activity: [],
    nodata: false,
    showWebview: false,
    console: console.log('打印首页数据', app),
    scopeUserInfo: false,
    isHiddenAll: false,
    isHasClassname: false,
    // scrollTop:0
    labelVideoData: '',//分类标签的数据
    labelVideoDataArr: [],//分类标签的存放的数据        
    labelVideoNum: 8,//分类标签首次加载8
    CategoryIdd: null,
    start: 0,
    // isHiddenStopPull:true,
    isStoponReachBottom: true,//防止上拉触底事件提前触发
    isSuccessGetData: false,
  },
  //事件处理函数
  onLoad: function (obj) {
    var self = this



    console.log('onload，首页加载', obj)

    //显示当前页面的转发按钮
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        console.log('显示页面的转发按钮', res);
      }
    })
  
  },

  onShow: function (obj) {
    var self = this;

    console.log('onshow，首页显示', obj)
    
    console.log('loginstatus', app.globalData.loginStatus)
    setTimeout(() => {
      self.setData({
        // loginStatus: app.globalData.loginStatus,
        AlreadyPracticed: app.globalData.AlreadyPracticed,
        hidePop: true,
        // activity: activity
      })
    }, 500);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (obj) {
    var that = this
    console.log('onReady，初次渲染完成', obj)
    that.getWeekDay(); //获取日期
    that.GetWechatIndexPage(); //获取首页数据
    // that.authorizePop = that.selectComponent('#authorizePop')
  },

  onHide: function () {
    var that = this;
  },
  //下拉刷新
  onPullDownRefresh: function (params) {
    var that = this;

    that.GetWechatIndexPage(null, function (params) {
      //数据加载完后停止刷新
      setTimeout(() => {
        console.log('停止刷新');
        wx.stopPullDownRefresh();
        that.setData({
          changeIndex: 2,
          hideloadmore: true,
        })
      }, 1000);
    })
  },

  // //上拉触底事件
  // onReachBottom: function (e) {
  //   // 页面上拉触底事件的处理函数
  //   var that = this;


  //   console.log('页面到底了', e);
  //   if (that.data.label_id == 0) {
  //     var VideoCategory = that.data.VideoCategory; //页面显示视频分类数据
  //     var CategoryListList = that.data.CategoryListList; //所有视频分类数据
  //     var changeIndex = that.data.changeIndex; //分类视频编号
  //     if (changeIndex >= CategoryListList.length) {
  //       that.setData({
  //         hideloadmore: false,
  //       })
  //       return
  //     }
  //     VideoCategory.push(CategoryListList[changeIndex]);
  //     CategoryListList[changeIndex + 1] && VideoCategory.push(CategoryListList[changeIndex + 1]);

  //     wx.showLoading({
  //       title: '加载中...',
  //     });
  //     setTimeout(() => {
  //       that.setData({
  //         VideoCategory: VideoCategory,
  //         changeIndex: changeIndex + 2

  //       })

  //       wx.hideLoading();

  //     }, 500);
  //   } else {
     
  //     var CategoryId = that.data.CategoryIdd;
  //     var labelVideoNum = that.data.labelVideoNum;
  //     var labelVideoData = that.data.labelVideoData;
  //     var start = that.data.start
  //     if (that.data.isStoponReachBottom) {
  //       if (that.data.labelVideoData.QuestionList.length < that.data.labelVideoNum) {
  //         that.setData({
  //           hideloadmore: false,
  //         })
  //         return
  //       } else {
  //         wx.showLoading({
  //           title: '加载中...',
  //         });
  //         setTimeout(() => {
  //           that.setData({
  //             labelVideoNum: 4,
  //             start: that.data.labelVideoDataArr.length + 4
  //           })
  //           that.GetLabelVideoData(CategoryId, that.data.start, that.data.labelVideoNum);
  //         }, 500)
  //       }

  //     }
    
  //   }
  // },

  //分享事件
  onShareAppMessage: function (res) {

    console.log('转发事件', res);

    // app.aldstat.sendEvent('首页-点击右上转发');
    // mta.Event.stat("home_clicktransmit", {});

    return {
      title: '像电影明星一样说英语！',
      desc: '天天口语秀',
      path: `/${path.dubbingIndex}?backflow=backflow`,
      imageUrl: `${path.images}shareImg.jpg`,
      success: function (res) {
        console.log('转发成功', res);
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });
      },
      fail: function (err) {
        console.log('转发失败', err)
      }
    }
  },

  //加载首页数据
  GetWechatIndexPage: function (params, cb) {
    var that = this;

    var dataDic = {
      openid: app.globalData.openId
    }
    api.methodGetWechatIndexPage({
      dataDic: dataDic,
      complete: function (res) {
        console.log(res.data)
        if (res.data.code != 0) {
          wx.showModal({
            title: '温馨提示',
            showCancel: false,
            content: res.data.msg || "数据请求失败",
          })
          return;
        } else {
          that.setData({
            DailyUpdatesList: res.data.data.DailyUpdatesList,
            HotRecommendationList: res.data.data.HotRecommendationList,
            CategoryListList: res.data.data.CategoryListList,
            VideoCategory: [res.data.data.CategoryListList[0], res.data.data.CategoryListList[1]],
            loadingHidden: true,
          })
        }
        typeof cb == 'function' && cb(res)
      }
    })
  },


  imgOnLoad(e) { //图片加载
    var that = this;

    // console.log('图片加载完成', e);
    const obj = e.currentTarget.dataset.obj;
    if (e.detail.height) {
      that.setData({
        [obj]: true
      })
    }
  },

  
  

  lookMore: function (e) {
    var that = this;

    var userObj = e.detail
    var getUserInfo = userObj.errMsg.split(':')

    if (getUserInfo[1] != 'ok') {
      Authorize.checkUserInfo(function (res) {
        if (!res) {
          that.setData({
            hidePop: false
          })
        } else {
          that.setData({
            hidePop: true
          })
        }
      }) //进入授权流程
      return
    } else {
      app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
      wx.setStorage({
        key: 'userInfo',
        data: userObj.userInfo,
        success: function (res) {
          console.log('用户信息存入缓存成功', res)
        }
      })
    }

    var loginStatus = app.globalData.loginStatus;
    if (loginStatus) {
      // app.aldstat.sendEvent('首页-每日推荐-点击查看更多（已登录）');
      // mta.Event.stat("home_clicklookmore_login", {});
      wx.navigateTo({
        url: '/' + path.dailyRecommend
      })
    } else {
      // app.aldstat.sendEvent('首页-每日推荐-点击查看更多（未登录）');
      // mta.Event.stat("home_clicklookmore_notlogin", {});
      wx.navigateTo({
        url: '/' + path.login
      })
    }
  },

  //去下一页
  getuserinfo(params) {
    var that = this

    console.log('点击下一页', params);
    var str = params.currentTarget.dataset.type;
    var isjoin = params.currentTarget.dataset.isjoin;
    var location = params.currentTarget.dataset.location;
    var qid = params.currentTarget.dataset.qid;
    var type = params.currentTarget.dataset.type;
    var userObj = params.detail;
    var getUserInfo = userObj.errMsg.split(':');

    // var aldStr = "首页-点击"
    // mta.Event.stat("home_click")

    if (location == 0) {
      // aldStr = "首页-点击每日一句";
      // mta.Event.stat("home_clickdailysentence");
    } else {
      // aldStr = "首页-点击-" + type + "-" + location;
      // var hotNumber = "home_click_hot";
      // mta.Event.stat(hotNumber, { 'classify': type, 'location': location });
    }
  
    // app.aldstat.sendEvent(aldStr, { 'classify': type });

    if (getUserInfo[1] != 'ok') {
      Authorize.checkUserInfo(function (res) {
        if (!res) {
          that.setData({
            hidePop: false
          })
        } else {
          that.setData({
            hidePop: true
          })
        }
      }) //进入授权流程
      return
    } else {
      app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
      wx.setStorage({
        key: 'userInfo',
        data: userObj.userInfo,
        success: function (res) {
          console.log('用户信息存入缓存成功', res)
        }
      })
      if (isjoin == 1 || app.globalData.AlreadyPracticed[qid]) {
        wx.navigateTo({
          url: '/' + path.scorePreview + '?QID=' + qid + '&type=' + str
        })
      } else {
        wx.navigateTo({
          url: '/' + path.details + '?QID=' + qid + '&type=' + type
        })
      }
    }

  },


  //获取星期日期
  getWeekDay: function () {
    var self = this
    var nowDate = new Date();
    var week = nowDate.getDay()
    var month = nowDate.getMonth() + 1
    var str = nowDate.getFullYear() + "-" + month + "-" + nowDate.getDate();

    self.setData({
      thisDay: str
    })

  },

  //收集formId
  saveFormId: tools.saveFormId,

  //关闭模态框
  cancel: function () {
    var that = this;

    // app.aldstat.sendEvent('首页-点击关闭大的注册弹窗');
    // mta.Event.stat("home_clickcloseregisterpopup", {});

    that.setData({
      hideModal: true,
      isPromptClose: false,
    })
  },

  //取消按钮被点击
  onCancelTap: function (e) {
    var that = this;

    console.log('取消按钮已点击', e);

    that.setData({
      hidePop: true
    })
    // wx.navigateBack({
    //     delta: 1, // 回退前 delta(默认为1) 页面
    // })
  },

  //确定按钮被点击
  onConfirmTap(e) {
    var that = this;

    console.log('确定按钮已点击', e);
    var type = e.detail.type;
    var detail = e.detail.detail;
    if (type == 'getUserInfo') {

    } else if (type == 'openSetting') {

    }
  },
  

})